package com.wending.application;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tencent.bugly.crashreport.CrashReport;
import com.wending.base_method.NetworkDetector;
import com.wending.base_method.ProcessMethod;
import com.wending.bean.User;
import com.wending.config.Constant;

import org.litepal.LitePalApplication;
import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.ShareSDK;

/**
 * Created by ${张英杰} on 2017/1/22.
 */

public class MyApplication extends LitePalApplication {
    public static RequestQueue requestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
        ShareSDK.initSDK(this);
        initBugly();
        requestQueue = Volley.newRequestQueue(this);
        Timer timerLogin=new Timer(true);
        timerLogin.schedule(taskLogin,0,15*60*1000);
//        timerLogin.schedule(taskLogin,0,8*1000);
    }

    private TimerTask taskLogin = new TimerTask() {
        @Override
        public void run() {
            Login();
        }
    };
    private int loginCount=0;
    StringRequest loginRequest;
    private void Login() {
        List<User> all = DataSupport.findAll(User.class);
        if (all != null && all.size() > 0 && all.get(0) != null) {
            User user = all.get(0);
            Log.i("user=====",user.toString());
            String url = Constant.Login + "?password=" + user.getPassword() + "&username=" + user.getUsername();
            loginRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    Log.i("AAAplication====",s+"");
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    loginCount++;
                    Log.i("AAAplication===="," loginCount=="+ loginCount+"--volleyError--"+volleyError.toString());
                    if (NetworkDetector.detect(MyApplication.this)&&loginCount<500){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(2000);
                                    requestQueue.add(loginRequest);
                                    requestQueue.start();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            }){
                //重写parseNetworkResponse方法，返回的数据中 Set-Cookie:***************;
                //其中**************为session id
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
//                return super.parseNetworkResponse(response);
                    Response<String> superResponse = super
                            .parseNetworkResponse(response);
                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    if (rawCookies == null) {
                        requestQueue.add(loginRequest);
                        requestQueue.start();
                    }else {
                        //Constant是一个自建的类，存储常用的全局变量
                        Constant.localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                        Log.d("AAAplication新的sessionid", "======" + Constant.localCookie);
                    }
                    return superResponse;
                }
            };
            requestQueue.add(loginRequest);
            requestQueue.start();
        }
    }

    private void initBugly() {
        Context context = getApplicationContext();
// 获取当前包名
        String packageName = context.getPackageName();
// 获取当前进程名
        String processName = ProcessMethod.getProcessName(android.os.Process.myPid());
// 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
//        CrashReport.initCrashReport(context, "af8f3b59b6", isDebug, strategy);
        CrashReport.initCrashReport(context, "af8f3b59b6", false, strategy);
// 如果通过“AndroidManifest.xml”来配置APP信息，初始化方法如下
// CrashReport.initCrashReport(context, strategy);
//        CrashReport.testJavaCrash();
    }
}
